package dao

import javax.inject.Inject
import models.Tables._
import play.api.db.slick.{DatabaseConfigProvider, HasDatabaseConfigProvider}
import play.db.NamedDatabase
import shared.VarTool
import slick.jdbc.JdbcProfile

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

/**
 * Created by yz on 2018/7/17
 */
class UserDao @Inject()(protected val dbConfigProvider: DatabaseConfigProvider) extends
  HasDatabaseConfigProvider[JdbcProfile] {

  import profile.api._

  def selectAll: Future[Seq[UserRow]] = db.run(User.result)

  def insert(row: UserRow): Future[Unit] = db.run(User += row).map(_ => ())

  def deleteById(id: Int): Future[Unit] = db.run(User.filter(_.id === id).delete).map(_ => ())

  def selectById(id: Int): Future[UserRow] = db.run(User.
    filter(_.id === id).result.head)

  def update(row: UserRow): Future[Unit] = db.run(User.filter(_.id === row.id).update(row)).
    map(_ => ())

  def selectByEmail(email: String): Future[Option[UserRow]] = db.run(User.
    filter(_.email === email).result.headOption)

  def selectByEmailSome(email: String) = db.run(User.
    filter(_.email === email).result.head)

  def selectOpByEmailAndPassword(email: String, password: String): Future[Option[UserRow]] = db.run(User.
    filter(x => x.email === email && x.password === password).result.headOption)

  def selectOpByEmailOrPhoneAndPassword(account: String, password: String): Future[Option[UserRow]] = db.run(User.
    filter(x => (x.email === account && x.password === password) || (x.phone === account && x.password === password)).
    result.headOption)

  def selectSomeByEmail(email: String): Future[UserRow] = db.run(User.
    filter(_.email === email).result.head)

  def selectOpByPhone(phone: String): Future[Option[UserRow]] = db.run(User.
    filter(_.phone === phone).result.headOption)

  def selectOpByEmail(email: String): Future[Option[UserRow]] = db.run(User.
    filter(_.email === email).result.headOption)

  def selectByPhone(phone: String) = db.run(User.
    filter(_.phone === phone).result.head)


}
